//
//  AirportObserver.m
//  Do Not Disturb
//
//  Created by Chris Karr on 8/28/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//
//	Credit iStumbler
//

#import "AirportObserver.h"
#import "DNDDefines.h"

#define AIRPORT_TOOL @"/System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport"

@implementation AirportObserver

+ (id) airportTool:(NSArray *) args
{
    NSTask * task = [NSTask new];
    NSData * output;
	
    [task setLaunchPath:AIRPORT_TOOL];
    [task setArguments:[args arrayByAddingObject:@"--xml"]];
    [task setStandardOutput:[NSPipe pipe]];
    [task setStandardError:[task standardOutput]];
	
    @synchronized (AIRPORT_TOOL)
    {
        [task launch];
        output = [[[task standardOutput] fileHandleForReading] readDataToEndOfFile];
    }
    
    [task release];
	
	id plist = nil;
		    
    if (output && [output length] > 0)
    {
        NSString* error;
     
        plist = [NSPropertyListSerialization propertyListFromData:output mutabilityOption:NSPropertyListImmutable 
					format:NULL errorDescription:&error];
        
        if (error)
			return [[[NSString alloc] initWithBytes:[output bytes] length:[output length] encoding:NSUTF8StringEncoding] autorelease];
    }
    
    return plist;
}

+ (NSArray *) availableNetworks
{
	return [AirportObserver airportTool:[NSArray arrayWithObject:@"-s"]];
}

+ (NSDictionary *) currentNetwork
{
	NSString * currentString = [AirportObserver airportTool:[NSArray arrayWithObject:@"-I"]];
	
	NSString * ssid = nil;
	NSString * bssid = nil;
	
	NSArray * lines = [currentString componentsSeparatedByString:@"\n"];
	NSEnumerator * iter = [lines objectEnumerator];
	NSString * line = nil;
	
	while ((line = [iter nextObject]) != nil)
	{
		if ([line rangeOfString:@"BSSID"].location != NSNotFound)
			bssid = [line substringFromIndex:17];
		else if ([line rangeOfString:@"SSID"].location != NSNotFound)
			ssid = [line substringFromIndex:17];
	}

	if ([ssid length] > 0)
	{
		NSMutableDictionary * dict = [NSMutableDictionary dictionary];
		[dict setValue:bssid forKey:@"BSSID"];
		[dict setValue:ssid forKey:@"SSID"];
	
		return dict;
	}
	else
		return nil;
}

- (void) scan
{
	NSDictionary * current = [AirportObserver currentNetwork];

	NSMutableDictionary * dict = [NSMutableDictionary dictionary];
	[dict setValue:[NSDate date] forKey:@"date"];
	
	if (current != nil)
	{
		[dict setValue:[NSString stringWithFormat:@"Current Wireless Network: %@ (%@)", [current valueForKey:@"SSID"],
				[current valueForKey:@"BSSID"]] forKey:@"name"];
		[dict setValue:current forKey:@"object"];
	}
	else
		[dict setValue:@"Current Wireless Network: <None>" forKey:@"name"];
	
	[[NSDistributedNotificationCenter defaultCenter] postNotificationName:DND_UPDATE object:@"AirportObserver" userInfo:dict];
	
	NSArray * networks = [AirportObserver availableNetworks];
	
	if (networks != nil)
	{
		NSEnumerator * iter = [networks objectEnumerator];
		NSDictionary * network = nil;
		
		while ((network = [iter nextObject]) != nil)
		{
			dict = [NSMutableDictionary dictionary];
			[dict setValue:[NSDate date] forKey:@"date"];

			[dict setValue:[NSString stringWithFormat:@"Available Wireless Network: %@ (%@)", [network valueForKey:@"SSID_STR"],
				[network valueForKey:@"BSSID"]] forKey:@"name"];

			[[NSDistributedNotificationCenter defaultCenter] postNotificationName:DND_UPDATE object:@"AirportObserver" userInfo:dict];
		}
	}
}

- (NSString *) getName
{
	return @"AirPort";
}


@end
